#include "playermanager.h"
#include <QLayout>
#include "keycontrollablemenu.h"
#include "messagedialog.h"

QList<FileSelectionInterface *> PlayerManager::selectors;
QWidget * PlayerManager::central;
QPushButton * PlayerManager::nowPlaying;
QPushButton * PlayerManager::playButton;
QPushButton * PlayerManager::stopButton;
QPushButton * PlayerManager::fastforwardButton;
QPushButton * PlayerManager::rewindButton;
QPushButton * PlayerManager::skipButton;
QPushButton * PlayerManager::previousButton;
QPushButton * PlayerManager::shuffleButton;
QPushButton * PlayerManager::repeatButton;
QPushButton * PlayerManager::muteButton;
QIcon ** PlayerManager::repeatImages;
QIcon ** PlayerManager::shuffleImages;
int PlayerManager::repeat;
bool PlayerManager::shuffle;
FileSelectionInterface * PlayerManager::currentInterface;
PlayerManager * PlayerManager::manager;
QWidget * PlayerManager::top;
QWidget * PlayerManager::bottom;
QWidget * PlayerManager::sliderHolder;
QWidget * PlayerManager::mainWidget;
Phonon::SeekSlider * PlayerManager::slider;


PlayerManager::PlayerManager()
{
    repeat=0;
    shuffle=0;
    repeatImages=new QIcon*[3];
    shuffleImages=new QIcon*[2];
    for(int i=0; i<3; i++) {
        repeatImages[i]=new QIcon(":/imgs/3F00Button_Repeat"+QString::number(i+1)+".png");
    }

    for(int i=0; i<2; i++) {
        shuffleImages[i]=new QIcon(":/imgs/3F00Button_Shuffle"+QString::number(i+1)+".png");
    }
}

void PlayerManager::setMainWidget(QWidget * widget) {
    mainWidget=widget;
}

void PlayerManager::addSelector(FileSelectionInterface * interface) {
    selectors.append(interface);
    QVBoxLayout * layout=qobject_cast<QVBoxLayout *>(central->layout());
    layout->addWidget(interface->getInterface(),0,Qt::AlignHCenter|Qt::AlignTop);
    interface->getInterface()->hide();
    interface->getInterface()->setMaximumSize(QApplication::desktop()->screen(0)->size());
}

void PlayerManager::setNowPlaying(QPushButton *button) {
    nowPlaying = button;
}

void PlayerManager::setPlayButton(QPushButton *button) {
    playButton = button;
}

void PlayerManager::setRewindButton(QPushButton *button) {
    rewindButton = button;
}

void PlayerManager::setStopButton(QPushButton *button) {
    stopButton = button;
}
void PlayerManager::setFastforwardButton(QPushButton * button) {
    fastforwardButton = button;
}

void PlayerManager::setSkipButton(QPushButton *button) {
    skipButton = button;
}

void PlayerManager::setPreviousButton(QPushButton *button) {
    previousButton = button;
}

void PlayerManager::setRepeatButton(QPushButton *button) {
    repeatButton = button;
    button->setIcon(*repeatImages[0]);
}

void PlayerManager::setShuffleButton(QPushButton *button) {
    shuffleButton = button;
    button->setIcon(*shuffleImages[0]);
}

FileSelectionInterface * PlayerManager::getFileSelector(QString extension) {
    foreach(FileSelectionInterface * interface,selectors) {
        if(interface->getExtensions().contains(extension)) {
            return interface;
        }
    }
    return NULL;
}

void PlayerManager::setPlayer(FileSelectionInterface * interface) {
    if(interface==currentInterface) {
        return;
    }
    if(currentInterface) { //Disconnects current media if other media starts to play
        currentInterface->stop();
        QObject::disconnect(PlayerManager::playButton,SIGNAL(clicked()),currentInterface,SLOT(play()));
        QObject::disconnect(PlayerManager::stopButton,SIGNAL(clicked()),currentInterface,SLOT(stop()));
        QObject::disconnect(PlayerManager::fastforwardButton,SIGNAL(clicked()),currentInterface,SLOT(fastForward()));
        QObject::disconnect(PlayerManager::rewindButton,SIGNAL(clicked()),currentInterface,SLOT(rewind()));
        QObject::disconnect(PlayerManager::skipButton,SIGNAL(clicked()),currentInterface,SLOT(next()));
        QObject::disconnect(PlayerManager::previousButton,SIGNAL(clicked()),currentInterface,SLOT(previous()));
        QObject::disconnect(PlayerManager::manager,SIGNAL(setShuffleState(bool)),currentInterface,SLOT(setShuffleState(bool)));
        QObject::disconnect(PlayerManager::manager,SIGNAL(setRepeatState(int)),currentInterface,SLOT(setRepeatState(int)));
        QObject::disconnect(KeyControllableMenu::volumeDisplay,SIGNAL(volumeChanged(int)),currentInterface,SLOT(setVolume(int)));
        QObject::disconnect(currentInterface,SIGNAL(stateChanged(bool)),manager,SLOT(setPlayState(bool)));
        QObject::disconnect(currentInterface,SIGNAL(error(QString)),manager,SLOT(errorReceived(QString)));
        QObject::disconnect(currentInterface,SIGNAL(fileChanged(QString,int,int)),manager,SLOT(updateNowPlaying(QString,int,int)));
    }
    currentInterface=interface;
    QObject::connect(PlayerManager::playButton,SIGNAL(clicked()),currentInterface,SLOT(play()));
    QObject::connect(PlayerManager::stopButton,SIGNAL(clicked()),currentInterface,SLOT(stop()));
    QObject::connect(PlayerManager::fastforwardButton,SIGNAL(clicked()),currentInterface,SLOT(fastForward()));
    QObject::connect(PlayerManager::rewindButton,SIGNAL(clicked()),currentInterface,SLOT(rewind()));
    QObject::connect(PlayerManager::skipButton,SIGNAL(clicked()),currentInterface,SLOT(next()));
    QObject::connect(PlayerManager::previousButton,SIGNAL(clicked()),currentInterface,SLOT(previous()));
    QObject::connect(PlayerManager::manager,SIGNAL(setShuffleState(bool)),currentInterface,SLOT(setShuffleState(bool)));
    QObject::connect(PlayerManager::manager,SIGNAL(setRepeatState(int)),currentInterface,SLOT(setRepeatState(int)));
    QObject::connect(KeyControllableMenu::volumeDisplay,SIGNAL(volumeChanged(int)),currentInterface,SLOT(setVolume(int)));
    QObject::connect(currentInterface,SIGNAL(stateChanged(bool)),manager,SLOT(setPlayState(bool)));
    QObject::connect(currentInterface,SIGNAL(error(QString)),manager,SLOT(errorReceived(QString)));
    QObject::connect(currentInterface,SIGNAL(fileChanged(QString,int,int)),manager,SLOT(updateNowPlaying(QString,int,int)));
    slider->setVisible(currentInterface->setSlider(slider));
    nowPlaying->show();
    nowPlaying->setEnabled(true);
    updateSize();
    emit manager->setShuffleState(shuffle);
    emit manager->setRepeatState(repeat);
}

QWidget * PlayerManager::getCurrentPlayer() {
    if(currentInterface) {
        return currentInterface->getInterface();
    }

    return NULL;
}

void PlayerManager::setCentralWidget(QWidget *centralWidget) {
    central=centralWidget;
}

void PlayerManager::setManager(PlayerManager * playerManager) {
    manager=playerManager;
}

void PlayerManager::interpretKeys(QKeyEvent *event) {
    if(currentInterface) {
        if(KeyBindings::matchesKeys(KeyBindings::playKey,event)) {
            currentInterface->play();
        }
        else if(KeyBindings::matchesKeys(KeyBindings::stopKey,event)) {
            currentInterface->stop();
        }
        else if(KeyBindings::matchesKeys(KeyBindings::ffKey,event)) {
            currentInterface->fastForward();
        }
        else if(KeyBindings::matchesKeys(KeyBindings::rwKey,event)) {
            currentInterface->rewind();
        }
        else if(KeyBindings::matchesKeys(KeyBindings::skipKey,event)) {
            currentInterface->next();
        }
        else if(KeyBindings::matchesKeys(KeyBindings::previousKey,event)) {
            currentInterface->previous();
        }
    }

    if(KeyBindings::matchesKeys(KeyBindings::fullscreenKey,event)) {
        qDebug() <<"switching full screen state";
        swapFullScreen();
    }
}

void PlayerManager::setPlayState(bool playing) {

    if(playing){
        playButton->setIcon (QIcon(":/imgs/3F00Button_Pause.png"));

    }
    else{
        playButton->setIcon (QIcon(":/imgs/3F00Button_Play.png"));

    }
}

void PlayerManager::shuffleClicked() {
    shuffle=!shuffle;
    if(shuffle) {
        shuffleButton->setIcon(*shuffleImages[1]);
    } else {
        shuffleButton->setIcon(*shuffleImages[0]);
    }
    emit manager->setShuffleState(shuffle);
}

void PlayerManager::repeatClicked() {
    repeat=(repeat+1)%3;
    repeatButton->setIcon(*repeatImages[repeat]);
    emit manager->setRepeatState(repeat);
}

void PlayerManager::swapFullScreen() {
    if(top->isVisible()) {
        top->hide();
        bottom->hide();
        QApplication::setOverrideCursor(Qt::BlankCursor);
        sliderHolder->hide();
        if(currentInterface) {
            currentInterface->getInterface()->showFullScreen();
            if(currentInterface->getName()!="Photos") {
                slider->hide();
            }
        }
    } else {
        top->show();
        bottom->show();
        QApplication::setOverrideCursor(Qt::ArrowCursor);
        sliderHolder->show();
        if(currentInterface) {
            if(currentInterface->getName()!="Photos") {
                slider->show();
            }
            currentInterface->getInterface()->showMaximized();
        }
    }
    updateSize();
}

void PlayerManager::setTop(QWidget *widget) {
    top=widget;
}

void PlayerManager::setBottom(QWidget *widget) {
    bottom=widget;
}

void PlayerManager::setSlider(Phonon::SeekSlider *seekSlider) {
    slider=seekSlider;
}

void PlayerManager::muteClicked() {
    if(currentInterface) {
        if(KeyControllableMenu::volumeDisplay->isMute()) {
           currentInterface->setVolume(0);
        } else {
            currentInterface->setVolume(KeyControllableMenu::volumeDisplay->getVolume());
        }
    }
}

void PlayerManager::setMuteButton(QPushButton *button) {
    muteButton=button;
    connect(button,SIGNAL(clicked()),manager,SLOT(muteClicked()));
}

void PlayerManager::errorReceived(QString error) {
    MessageDialog::showDialog(error,NULL);
}

void PlayerManager::updateNowPlaying(QString fileName, int index, int queueSize) {
    QString name=QFileInfo(fileName).completeBaseName();
    nowPlaying->setText("Now Playing: "+name+" ("+QString::number(index+1)+" / "+QString::number(queueSize)+")");
}

void PlayerManager::setSliderHolder(QWidget *widget) {
    sliderHolder=widget;
}

void PlayerManager::updateSize() {
    if(currentInterface) {
        if(top->isVisible()) {
            currentInterface->getInterface()->setMinimumWidth(central->width());
            currentInterface->getInterface()->setMinimumHeight(mainWidget->height()-top->height()-bottom->height());
        } else {
            currentInterface->getInterface()->setMinimumHeight(mainWidget->height());
        }
    }
}

bool PlayerManager::isCurrentAPlayer() {
    return currentInterface->getInterface()==WindowManager::getCurrent();
}
